//
//  LZHomeViewController.swift
//  Weibo
//
//  Created by lzing on 16/3/21.
//  Copyright © 2016年 lzing. All rights reserved.
//

import UIKit
import SVPullToRefresh

class LZHomeViewController: LZBaseTableViewController {
    
    private let ReuseIdentifier = "cell"
    
    /// 模型数据
    var statuses : [LZStatus]? {
        didSet {
            self.tableView.reloadData()
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        // 如果没登录,则不设置导航条
        if !LZUserAccountViewModel.sharedUserAccountViewModel.userLoginStatus {
            return
        }
        // 设置导航栏
        setupTitleButtonItem()
        setupBarButtonItem()
        // 设置tableView属性
        prepareTableView()
        
    }
    
    private func prepareTableView() {
        // 注册cell
        tableView.registerClass(LZStatusCell.self, forCellReuseIdentifier: ReuseIdentifier)
        // 设置约束根据控件
        tableView.rowHeight = UITableViewAutomaticDimension
        // 设置预估高度影响tableView的帧数
//        tableView.estimatedRowHeight = 80
        // 取消分割线
        tableView.separatorStyle = UITableViewCellSeparatorStyle.None
        // 刷新控件回调方法
        tableView.addPullDownRefreshHandler { [weak self] () -> () in
            self?.loadNewStatus()
        }
        // 开始刷新
        tableView.startRefreshing()
    }
    
    ///  加载新数据
    private func loadNewStatus() {
        // 获得id最大微博, 当没有微博数据,传入0加载最新20条微博数据
        let since_id = self.statuses?.first?.id ?? 0
        // 使用VM加载数据
        LZStatusView.sharedStatusView.loadStatus(since_id, max_id: 0) { [weak self] (statuses, error) -> () in
            // 结束刷新
            self?.tableView.endRefreshing()
            // 如果有错误
            if error != nil {
                LZPrint(msg: "加载微博数据出错")
                return
            }
            let count = statuses?.count ?? 0
            
            if count == 0 {
                LZPrint(msg: "没有加载到微博")
                return
            }
            // 下拉刷新
            if since_id > 0 {
                // 显示刷新label
                self?.showTipLabel(count)
//                LZPrint(msg: "下拉刷新count: \(count)")
                // 下拉刷新,需要将新获取到的数据添加到模型数据中
                self?.statuses = statuses! + self!.statuses!
            } else {
//                LZPrint(msg: "第一次加载最新微博count: \(count)")
                // 加载最新的20条数据
                self?.statuses = statuses
                // 当第一次获取数据完成后再添加上拉加载更多功能
                self?.tableView.addInfiniteScrollingWithActionHandler({ () -> Void in
                    self?.loadMoreStatus()
                })
            }
            // 最终加载的数据
//            LZPrint(msg: "最终微博数据条数: \(self?.statuses?.count)")
        }
    }
    
    ///  加载更多微博数据
    private func loadMoreStatus() {
        let max_id = self.statuses?.last?.id ?? 0
        LZStatusView.sharedStatusView.loadStatus(0, max_id: max_id) { [weak self] (statuses, error) -> () in
            // 结束上拉加载数据
            self?.tableView.infiniteScrollingView.stopAnimating()
            // 如果错误不为空
            if error != nil {
                LZPrint(msg: "上拉加载微博数据出错了: \(error)")
                return
            }
            let count = statuses?.count ?? 0
            if count == 0 {
                LZPrint(msg: "没有加载到微博")
                return
            }
            // 上拉加载数据拼接在当前模型数据的后面
            self?.statuses = self!.statuses! + statuses!
//            LZPrint(msg: "上拉加载更多数据: \(statuses?.count)")
//            LZPrint(msg: "最终微博数据条数: \(self!.statuses?.count)")
        }
    
    }
    
    //MARK: - show refresh count
    private func showTipLabel(count: Int) {
        tipLabel.text = count == 0 ? "没有新的微博数据" : "更新了\(count)条微博数据"
        
        // 防止连续刷新时导致控件位置不准确
        let animationKeys = tipLabel.layer.animationKeys()
        // 有动画在执行
        if animationKeys != nil {
            // 移除动画
            LZPrint(msg: "有动画正在执行")
            tipLabel.layer.removeAllAnimations()
        }
        
        // 开启动画隐藏view
        UIView.animateWithDuration(LZDefaultDuration * 4, animations: {[weak self] () -> Void in
            self?.tipLabel.frame.origin.y = 44
            }) { (_) -> Void in
                UIView.animateWithDuration(LZDefaultDuration * 4, delay: LZDefaultDuration * 2, options: UIViewAnimationOptions(rawValue: 0), animations: { () -> Void in
                    self.tipLabel.frame.origin.y = -64
                    }, completion: { (_) -> Void in
                        self.tipLabel.removeFromSuperview()
                })
        }
    }
    
    //MARK: - prepareNavigationBar
    private func setupTitleButtonItem() {
        let title = ((LZUserAccountViewModel.sharedUserAccountViewModel.userAccount?.screen_name) != nil) ? LZUserAccountViewModel.sharedUserAccountViewModel.userAccount?.screen_name : "weibo"
        let titleButton = LZTitleButton(title: title!, imageName: "navigationbar_arrow_down", target: self, action: "titleButtonDidClick:")
        navigationItem.titleView = titleButton
    }
    
    private func setupBarButtonItem() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: "navigationbar_friendattention", target: self, action: "leftBarButtonItemDidClick")
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(imageName: "navigationbar_pop", target: self, action: "rightBarButtonItemDidClick")
    }
    
    //MARK: - BarButtonItemDidClick
    @objc private func leftBarButtonItemDidClick() {
        
    }
    
    @objc private func rightBarButtonItemDidClick() {
        
    }
    
    @objc private func titleButtonDidClick(button : LZTitleButton) {
        button.selected = !button.selected
        // 旋转按钮
        UIView.animateWithDuration(LZDefaultDuration) { () -> Void in
            button.imageView?.transform = button.selected ? CGAffineTransformMakeRotation(CGFloat(M_PI - 0.001)) : CGAffineTransformIdentity
        }
        
        // 如果是选中状态,弹出poperVC
        if button.selected {
            let popoverVC = LZPopoverViewController()
            // 设置modal样式
            popoverVC.modalPresentationStyle = .Popover
            // 设置代理
            popoverVC.popoverPresentationController?.delegate = self
            // 设置箭头位置
            popoverVC.popoverPresentationController?.sourceView = navigationItem.titleView
            // 设置箭头sourceRect
            popoverVC.popoverPresentationController?.sourceRect = navigationItem.titleView!.bounds
            // 设置popover显示的大小
            popoverVC.preferredContentSize = CGSize(width: 200, height: 44 * popoverVC.titles.count)
            // 弹出
            presentViewController(popoverVC, animated: true, completion: nil)
        }
    }
    
    //MARK: - 懒加载
//    private lazy var pullDownRefreshControl : PullDownRefreshControl = PullDownRefreshControl(frame: CGRect(x: 10, y: 10, width: 10, height: 10))
    private lazy var tipLabel : UILabel = {
        let tipLabel = UILabel()
        tipLabel.backgroundColor = UIColor.orangeColor()
        tipLabel.textColor = UIColor.whiteColor()
        tipLabel.font = UIFont.systemFontOfSize(16)
        tipLabel.textAlignment = NSTextAlignment.Center
        tipLabel.frame = CGRect(x: 0, y: -64, width: UIScreen.width, height: 44)
        
        // 往navigation上添加
        self.navigationController?.navigationBar.insertSubview(tipLabel, atIndex: 0)
        
        return tipLabel
    }()
    
}

//MARK: - UITableViewDelegate, UITableViewDataSource
extension LZHomeViewController {
    // 返回行个数
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return statuses?.count ?? 0
    }
    
    // cell的个数
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        // 注册cell
        let cell = tableView.dequeueReusableCellWithIdentifier(ReuseIdentifier, forIndexPath: indexPath) as! LZStatusCell
        
        cell.status = statuses?[indexPath.row]
        
        return cell
    }
    
    // 返回行高
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        // 取出模型
        let status = self.statuses![indexPath.row]
        // 模型中有高度
        if status.rowHeight != nil {
            return status.rowHeight!
        }
        // 没有缓存过高度
        // 取出cell
        let cell = tableView.dequeueReusableCellWithIdentifier(ReuseIdentifier) as! LZStatusCell
        // 赋值模型
        cell.status = status
        // 取出行高
        let rowHeight = cell.systemLayoutSizeFittingSize(UILayoutFittingExpandedSize).height
        // 记录行高
        status.rowHeight = rowHeight
        // 返回行高
        return rowHeight
    }
    
    // 取消高亮效果
    override func tableView(tableView: UITableView, shouldHighlightRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        return false
    }
}


//MARK: - UIPopoverPresentationControllerDelegate
extension LZHomeViewController : UIPopoverPresentationControllerDelegate {
    
    //MARK: - adaptiveView
    func adaptivePresentationStyleForPresentationController(controller: UIPresentationController) -> UIModalPresentationStyle {
        return UIModalPresentationStyle.None
    }
    //MARK: - close PopoverView
    func popoverPresentationControllerShouldDismissPopover(popoverPresentationController: UIPopoverPresentationController) -> Bool {
        let titleButton = navigationItem.titleView as! LZTitleButton
        titleButtonDidClick(titleButton)
        return true
    }
}
